package com.cancan.cloud.shop.threadContext;

public final class ThreadContextManage {

	private static volatile ThreadLocal<ThreadContext> threadLocal = new ThreadLocal<>();
	
	public static ThreadContext getThreadContext() {
		ThreadContext threadContext = threadLocal.get();
		if (threadContext == null) {
			synchronized(ThreadContextManage.class) {
				if (threadContext == null) {
					threadContext = new ThreadContext();
					threadLocal.set(threadContext);
				}
			}
		}
		return threadContext;
	}
	
	public static void clearThreadContext() {
		threadLocal.remove();
	}

	public static void makeThreadContextEmpty() {
		//ThreadLocal中拿到的永远只有一个线程正在操作，是安全的
		ThreadContext threadContext = threadLocal.get();
		//清除内容而非null，不用频繁创建对象
		if (threadContext != null) {
			threadContext.getVariables().clear();
		}
	}
	
}
